package mq.workQueues;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import mq.Constants.Constants;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author: Themberfue
 * @date: 2025/4/27 19:10
 * @description:
 */
public class Producer {
    public static void main(String[] args) throws IOException, TimeoutException {
        // TODO 1. 建立连接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(Constants.HOST);
        connectionFactory.setPort(Constants.PORT);
        connectionFactory.setUsername(Constants.USER_NAME);
        connectionFactory.setPassword(Constants.PASSWORD);
        connectionFactory.setVirtualHost(Constants.VIRTUAL_HOST);
        Connection connection = connectionFactory.newConnection();

        //  TODO 2. 开启信道
        Channel channel = connection.createChannel();

        // TODO 3. 声明交换机（使用内置的交换机）

        // TODO 4. 声明队列
        channel.queueDeclare(Constants.WORK_QUEUE, true, false, false, null);

        // TODO 5. 发送消息
        for (int i = 0; i < 10; i++) {
            String msg = "hello work queue mode~：" + i;
            channel.basicPublish("", Constants.WORK_QUEUE, null, msg.getBytes(StandardCharsets.UTF_8));
        }

        System.out.println("消息发送成功");

        // TODO 6. 释放资源
        channel.close(); // ! 先关闭 channel
        connection.close();
    }
}
